//
//  ChatBoxView.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/23.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "ChatBoxView.h"
#import "PPStickerTextView.h"
#import "PPStickerDataManager.h"
#import "NSAttributedString+PPAddition.h"
#import "NSString+TextSize.h"
#import "RecordingHudView.h"
#import "VoiceRecordHelper.h"
#import "CacheHelper.h"
#import <YYText.h>

@interface ChatBoxView ()<UITextViewDelegate, YYTextViewDelegate>

@property (nonatomic, strong) VoiceRecordHelper *record;
@property (nonatomic, strong) RecordingHudView *hudView;


@property (nonatomic, strong) UIButton *voiceBtn;
@property (nonatomic, strong) UIButton *talkBtn;
@property (nonatomic, strong) YYTextView *textView;
@property (nonatomic, strong) UIButton *faceBtn;
@property (nonatomic, strong) UIButton *moreBtn;
@property (nonatomic, strong) UIButton *sendBtn;

@property (nonatomic, strong) UIButton *selectedBtn;

@property (nonatomic, strong) MASConstraint *faceRightLayoutWithMoreBtn;
@property (nonatomic, strong) MASConstraint *faceRightLayoutWithSendBtn;
@property (nonatomic, strong) MASConstraint *sendBtnLayoutForWidth;

@property (nonatomic, strong) MASConstraint *talkBtnTopLayout;

@property (nonatomic, strong) MASConstraint *textContentViewTopLayout;
@property (nonatomic, strong) MASConstraint *textViewLyoutForHeight;
@property (nonatomic, strong) MASConstraint *textContentViewLayoutForHeight;

@property (nonatomic, assign) CGFloat keyboardHeight;
@end

@implementation ChatBoxView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        [self setupRecordHelper];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        @weakify(self);
        [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            if (self.window == nil) {
                return;
            }
            NSDictionary *userInfo = [x userInfo];
            CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
            self.keyboardHeight = keyboardFrame.size.height;
            if (self.keyboardHeight > 10) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(chatBox:changeChatBoxViewHeight:)]) {
                    [self.delegate chatBox:self changeChatBoxViewHeight:self.keyboardHeight];
                }
            }
        }];
        [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillHideNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            if (self.window == nil) {
                return;
            }
            if (self.status == ChatBoxStatusKeyboard) {
                [self changeStatusTo:ChatBoxStatusNothing];
//                if (self.delegate && [self.delegate respondsToSelector:@selector(chatBox:changeChatBoxViewHeight:)]) {
//                    [self.delegate chatBox:self changeChatBoxViewHeight:0];
//                }
            }
        }];
    }
    return self;
}
- (void)setupUI {
    self.layer.cornerRadius = 5.0f;
    self.hudView = [RecordingHudView new];
    
    self.voiceBtn = UIButton.k_initType(UIButtonTypeCustom).k_img(UIImage.k_imgName(@"msg_box_voice")).k_img_state(UIImage.k_imgName(@"msg_box_keyboard"), UIControlStateSelected);
    self.faceBtn = UIButton.k_initType(UIButtonTypeCustom).k_img(UIImage.k_imgName(@"msg_box_face")).k_img_state(UIImage.k_imgName(@"msg_box_keyboard"), UIControlStateSelected);
    self.moreBtn = UIButton.k_initType(UIButtonTypeCustom).k_img(UIImage.k_imgName(@"msg_box_more"));
    self.moreBtn.frame = CGRectMake(0, 0, 30, 30);
    
    self.sendBtn = UIButton.k_initType(UIButtonTypeCustom).k_title(@"发送").k_bgImgColor(UIColor.k_t1Color);
    self.sendBtn.k_cornerRadius(3.0f).k_font([UIFont systemFontOfSize:15]);
    
    self.textView = [[YYTextView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.textView.backgroundColor = UIColor.k_hexColor(0xf7f7f7);
    self.textView.font = [UIFont systemFontOfSize:15];
    self.textView.placeholderText = @"请输入消息...";
    self.textView.placeholderTextColor = UIColor.k_t4Color;
    self.textView.textColor = UIColor.k_t2Color;
//    self.textView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.textView.textContainerInset = UIEdgeInsetsMake(0 , 0, 0, 0);
    self.textView.delegate = self;
//    self.textView.layoutManager.allowsNonContiguousLayout = NO;
//    self.textView.textContainer.lineFragmentPadding = 0;
    self.textView.contentInset = UIEdgeInsetsZero;
    self.textView.scrollEnabled = NO;

    UIView*textContentView = [UIView new];
    textContentView.backgroundColor = self.textView.backgroundColor;
    textContentView.layer.cornerRadius = 3.f;

    self.talkBtn.k_cornerRadius(3.0f);
    self.talkBtn.hidden = YES;
    
    [self addSubview:self.voiceBtn];
    [self addSubview:textContentView];
    [textContentView addSubview:self.textView];
    [self addSubview:self.talkBtn];
    [self addSubview:self.faceBtn];
    [self addSubview:self.moreBtn];
    [self addSubview:self.sendBtn];
    self.backgroundColor = UIColor.whiteColor;
    
    
    
    [self.voiceBtn addTarget:self action:@selector(didClickVoiceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.faceBtn addTarget:self action:@selector(didClickFaceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.moreBtn addTarget:self action:@selector(didClickMoreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sendBtn addTarget:self action:@selector(didClickSendMsgBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(Box_Margin);
        make.bottom.equalTo(textContentView).offset(-5);
        make.size.mas_equalTo(CGSizeMake(Box_Btn_Size, Box_Btn_Size));
    }];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_offset(5);
        make.right.mas_offset(-5);
//        make.top.mas_offset(3);
//        make.bottom.mas_offset(-3);
        self.textViewLyoutForHeight = make.height.mas_equalTo(20);
        make.centerY.mas_offset(0);
        
    }];
    [textContentView mas_makeConstraints:^(MASConstraintMaker *make) {
 
        make.left.equalTo(self.voiceBtn.mas_right).offset(Box_Margin);
        make.right.equalTo(self.faceBtn.mas_left).offset(-Box_Margin);
        self.textContentViewTopLayout = make.top.mas_offset(10);
        
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.mas_safeAreaLayoutGuideBottom).offset(-10);
        } else {
            make.bottom.mas_offset(-10);
        }
       self.textContentViewLayoutForHeight = make.height.mas_equalTo(34);
    }];
    [self.talkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.voiceBtn.mas_right).offset(Box_Margin);
        make.right.equalTo(self.faceBtn.mas_left).offset(-Box_Margin);
        make.bottom.equalTo(textContentView);
        make.height.mas_equalTo(34);
        self.talkBtnTopLayout = make.top.mas_offset(10);
    }];
    [self.talkBtnTopLayout deactivate];
    [self.faceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.voiceBtn);
        make.size.equalTo(self.voiceBtn);
        self.faceRightLayoutWithMoreBtn = make.right.equalTo(self.moreBtn.mas_left).offset(-Box_Margin);
        self.faceRightLayoutWithSendBtn = make.right.equalTo(self.sendBtn.mas_left).offset(-Box_Margin);
    }];
    [self.faceRightLayoutWithSendBtn deactivate];
    [self.moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.voiceBtn);
        make.size.equalTo(self.voiceBtn);
        make.right.mas_offset(-Box_Margin);
    }];
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-Box_Margin);
        make.centerY.equalTo(self.voiceBtn);
        make.height.mas_equalTo(Box_Btn_Size);
        self.sendBtnLayoutForWidth = make.width.mas_equalTo(0);
    }];
}
- (UIButton *)talkBtn {
    if (_talkBtn == nil) {
        _talkBtn = UIButton.k_initType(UIButtonTypeCustom).k_title(@"按住  说话");
        _talkBtn.k_font([UIFont systemFontOfSize:15]);
        _talkBtn.k_title(@"按住  说话").k_titleColor(UIColor.k_t3Color);
        _talkBtn.k_bgColor(UIColor.k_hexColor(0xf7f7f7));
        
        _talkBtn.hidden = YES;
        [_talkBtn addTarget:self action:@selector(talkBtnTouchDownAction:) forControlEvents:UIControlEventTouchDown];
        [_talkBtn addTarget:self action:@selector(talkBtnTouchInsideAction:) forControlEvents:UIControlEventTouchUpInside];
        [_talkBtn addTarget:self action:@selector(talkBtnTouchInsideAction:) forControlEvents:UIControlEventTouchUpOutside];
        [_talkBtn addTarget:self action:@selector(talkBtnTouchInsideAction:) forControlEvents:UIControlEventTouchCancel];
        [_talkBtn addTarget:self action:@selector(talkBtnTouchDragInsideAction:) forControlEvents:UIControlEventTouchDragInside];
        [_talkBtn addTarget:self action:@selector(talkBtnTouchDragOutsideAction:) forControlEvents:UIControlEventTouchDragOutside];
    }
    return _talkBtn;
}

- (void)adjustInputViewHeight {
    
    NSAttributedString *str = self.textView.attributedText;
//    CGFloat strWidth = self.textView.width - self.textView.textContainerInset.left- self.textView.textContainer.lineFragmentPadding*2-self.textView.textContainerInset.right;
    CGFloat strWidth = self.textView.width - self.textView.textContainerInset.left-self.textView.textContainerInset.right;
//    CGFloat textHeight = [str textHeightWithWidth:strWidth];
   
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:CGSizeMake(strWidth, CGFLOAT_MAX) text:str];
    CGFloat textHeight = layout.textBoundingSize.height;
    self.textView.scrollEnabled = NO;
    NSLog(@"------------- %f", textHeight);
    if (textHeight < 34) {
        
        self.textContentViewLayoutForHeight.offset(34);
        self.textViewLyoutForHeight.offset(20);
        
    }  else if (textHeight > 100) {//实测106
        self.textView.scrollEnabled = YES;
        self.textContentViewLayoutForHeight.offset(107+6);
        self.textViewLyoutForHeight.offset(107);
    } else {
        
        self.textContentViewLayoutForHeight.offset(textHeight+6);
        self.textViewLyoutForHeight.offset(textHeight);
    }
    [UIView animateWithDuration:0.3 animations:^{    
        [self.superview.superview layoutIfNeeded];
    }];
//    [self layoutIfNeeded];
}

- (void)addEmojiFace:(ChatFaceItem *)face {
//    self.textView.text = [self.textView.text stringByAppendingString:face.face_name];
    UIImage *emojiImage = UIImage.k_imgName(face.face_name);
    if (!emojiImage) {
        return;
    }
    NSString *emojiString = face.face_name;
    NSRange selectedRange = self.textView.selectedRange;

//    NSMutableAttributedString *emojiAttributedString = [[NSMutableAttributedString alloc] initWithString:emojiString];
//    [emojiAttributedString pp_setTextBackedString:[PPTextBackedString stringWithString:emojiString] range:emojiAttributedString.pp_rangeOfAll];
//
//    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
//    [attributedText replaceCharactersInRange:selectedRange withAttributedString:emojiAttributedString];
////    self.textView.text = face.face_name;
//    self.textView.attributedText = attributedText;
//    self.textView.selectedRange = NSMakeRange(selectedRange.location + emojiAttributedString.length, 0);
    
    
    
    NSMutableAttributedString *attributedComment = [[NSMutableAttributedString alloc] initWithString:emojiString attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:15], NSForegroundColorAttributeName: UIColor.k_t2Color }];
    [PPStickerDataManager.sharedInstance replaceEmojiForAttributedString:attributedComment font:[UIFont boldSystemFontOfSize:15]];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 3;
    [attributedComment addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:attributedComment.pp_rangeOfAll];
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    [attributedText replaceCharactersInRange:selectedRange withAttributedString:attributedComment];
    self.textView.attributedText = attributedText;
    self.textView.selectedRange = NSMakeRange(selectedRange.location + attributedComment.length, 0);

//    [self textViewDidChange:self.textView];
}
- (void)sendCurrentMsg {
    
}
- (void)deleteButtonDown {

    NSRange selectedRange = self.textView.selectedRange;
    if (selectedRange.location == 0 && selectedRange.length == 0) {
        return;
    }
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    if (selectedRange.length > 0) {
        [attributedText deleteCharactersInRange:selectedRange];
        self.textView.attributedText = attributedText;
        self.textView.selectedRange = NSMakeRange(selectedRange.location, 0);
    } else {
        NSUInteger deleteCharactersCount = 1;
        //  系统emoji
        NSString *emojiPattern1 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900-\\U0001F9FF]";
        NSString *emojiPattern2 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF]\\uFE0F";
        NSString *emojiPattern3 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF][\\U0001F3FB-\\U0001F3FF]";
        NSString *emojiPattern4 = @"[\\rU0001F1E6-\\U0001F1FF][\\U0001F1E6-\\U0001F1FF]";
        NSString *pattern = [[NSString alloc] initWithFormat:@"%@|%@|%@|%@", emojiPattern4, emojiPattern3, emojiPattern2, emojiPattern1];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:NULL];
        NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:attributedText.string options:kNilOptions range:NSMakeRange(0, attributedText.string.length)];
        for (NSTextCheckingResult *match in matches) {
            if (match.range.location + match.range.length == selectedRange.location) {
                deleteCharactersCount = match.range.length;
                break;
            }
        }
        
        [attributedText deleteCharactersInRange:NSMakeRange(selectedRange.location - deleteCharactersCount, deleteCharactersCount)];
        self.textView.attributedText = attributedText;
        self.textView.selectedRange = NSMakeRange(selectedRange.location - deleteCharactersCount, 0);
    }

//    [self textViewDidChange:self.textView];
}

#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(YYTextView *)textView {
    
    return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
    self.selectedBtn.selected = NO;
    self.selectedBtn = nil;
    [self changeStatusTo:ChatBoxStatusKeyboard];
}
//- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    
//    
//    if ([[PPStickerDataManager sharedInstance] matchingEmojiForString:text].count > 0 ) {
//        NSMutableAttributedString *attributedComment = [[NSMutableAttributedString alloc] initWithString:text attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:15], NSForegroundColorAttributeName: UIColor.k_t2Color }];
//        [PPStickerDataManager.sharedInstance replaceEmojiForAttributedString:attributedComment font:[UIFont boldSystemFontOfSize:15]];
//        
//        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//        paragraphStyle.lineSpacing = 3;
//        [attributedComment addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:attributedComment.pp_rangeOfAll];
//        if (textView.attributedText.length > 0) {
//            NSAttributedString *str11 = textView.attributedText;
//            NSMutableAttributedString *muStr11 = [[NSMutableAttributedString alloc] initWithAttributedString:str11];
//            [muStr11 appendAttributedString:attributedComment];
//            textView.attributedText = muStr11;
//        } else {
//            textView.attributedText = attributedComment;
//        }
//        return NO;
//    } else {
//        return YES;
//    }
//}
- (void)textViewDidChange:(YYTextView *)textView {
    
//    [self refreshTextUI];
    [self adjustInputViewHeight];
    [self.textView scrollRangeToVisible:self.textView.selectedRange];

    
    if([NSString isEmpty:self.textView.attributedText.string] == NO && self.moreBtn.alpha == 1) {
        
        [self.faceRightLayoutWithMoreBtn deactivate];
        [self.faceRightLayoutWithSendBtn activate];
        self.sendBtnLayoutForWidth.offset(40);
        [UIView animateWithDuration:0.2 animations:^{
            self.moreBtn.alpha = 0;
        }];
        
    } else if ((self.textView.attributedText.length == 0 && self.moreBtn.alpha == 0) || ([NSString isEmpty:self.textView.attributedText.string] == YES && self.moreBtn.alpha == 0)) {
        [self.faceRightLayoutWithMoreBtn activate];
        [self.faceRightLayoutWithSendBtn deactivate];
        self.sendBtnLayoutForWidth.offset(0);
        [UIView animateWithDuration:0.4 animations:^{
            self.moreBtn.alpha = 1;
        }];
    }
}
//- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    if (textView.text.length > 0 && [text isEqualToString:@""]) {
//        if ([textView.text characterAtIndex:range.location] == ']') {
//            NSUInteger location = range.location;
//            NSUInteger length = range.length;
//            while (location != 0) {
//                location --;
//                length ++;
//                char c = [textView.text characterAtIndex:location];
//                if (c == '[') {
//                    textView.text = [textView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
//                    return NO;
//                } else if (c == ']') {
//                    return YES;
//                }
//            }
//        }
//    }
//    return YES;
//}

//- (void)refreshTextUI
//{
//    if (!self.textView.text.length) {
//        return;
//    }
//
//    UITextRange *markedTextRange = [self.textView markedTextRange];
//    UITextPosition *position = [self.textView positionFromPosition:markedTextRange.start offset:0];
//    if (position) {
//        return;     // 正处于输入拼音还未点确定的中间状态
//    }
//
//    NSRange selectedRange = self.textView.selectedRange;
//
//    NSMutableAttributedString *attributedComment = [[NSMutableAttributedString alloc] initWithString:self.plainText attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:15], NSForegroundColorAttributeName: UIColor.k_t2Color }];
//
//    // 匹配表情
//    [PPStickerDataManager.sharedInstance replaceEmojiForAttributedString:attributedComment font:[UIFont boldSystemFontOfSize:15]];
//
//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//    paragraphStyle.lineSpacing = 3;
//    [attributedComment addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:attributedComment.pp_rangeOfAll];
//
//    NSUInteger offset = self.textView.attributedText.length - attributedComment.length;
//    self.textView.attributedText = attributedComment;
//    self.textView.selectedRange = NSMakeRange(selectedRange.location - offset, 0);
//}
- (NSString *)plainText
{
    return [self.textView.attributedText pp_plainTextForRange:NSMakeRange(0, self.textView.attributedText.length)];
}

#pragma mark - 录音 action
///  talkBtnAction
- (void)talkBtnTouchDownAction:(UIButton *)sender {
    sender.k_title(@"松开  结束").k_titleColor(UIColor.k_t2Color);
    sender.k_bgColor(UIColor.k_hexColor(0xeeeeee));
    [self.hudView show];
    self.hudView.status = 0;
    
    NSString *fileName = [[CacheHelper helper] newFileNameForMsgType:MsgType_Voice];
    NSString *filePath = [Cache_Help allFilePathWithMsgType:MsgType_Voice fileName:fileName];
    [self.record prepareRecordingWithPath:filePath prepareRecorderCompletion:^BOOL{
        return YES;
    }];
    [self.record startRecordingWithStartRecorderCompletion:^{
    }];
}
- (void)talkBtnTouchInsideAction:(UIButton *)sender {
    sender.k_title(@"按住  说话").k_titleColor(UIColor.k_t3Color);
    sender.k_bgColor(UIColor.k_hexColor(0xf7f7f7));
//    [self.hudView hide];
    @weakify(self);
    if (self.hudView.status == 0) {
        self.hudView.status = -1;
        [self.record stopRecordingWithStopRecorderCompletion:^(NSString * _Nullable path) {
            @strongify(self);
            [self sendVoiceRecordMsgWithPath:path voiceDuration:self.record.recordDuration.floatValue];
        }];
    } else if(self.hudView.status == 1) {
        [self.record cancelledDeleteWithCompletion:^(NSError * _Nullable error) {
            @strongify(self);
            [self.hudView hide];
        }];
    }
}
- (void)talkBtnTouchDragInsideAction:(UIButton *)sender {
    //  拖入
    if (self.hudView.status >= 0) {
        self.hudView.status = 0;
    }
}
- (void)talkBtnTouchDragOutsideAction:(UIButton *)sender {
    //  拖出
    if (self.hudView.status >= 0) {
        self.hudView.status = 1;
    }
}
#pragma mark VoiceRecordHelper
- (void)setupRecordHelper {
    self.record = [VoiceRecordHelper new];
    @weakify(self);
    [self.record setMaxTimeStopRecorderCompletion:^(NSString * _Nullable xpath) {
        @strongify(self);
//        [self.record stopRecordingWithStopRecorderCompletion:^(NSString * _Nullable path) {
//            [self sendVoiceRecordMsgWithPath:path voiceDuration:self.record.recordDuration.floatValue];
//            self.talkBtn.enabled = NO;
//            self.talkBtn.enabled = YES;
//            self.hudView.status = -1;
//            [self.hudView hide];
//        }];
        [self talkBtnTouchInsideAction:self.talkBtn];
    }];
    [self.record setRecordProgress:^(float progress) {
        @strongify(self);
        NSLog(@"progress = %f", progress);
        self.hudView.progress = progress;
    }];
}
- (void)sendVoiceRecordMsgWithPath:(NSString *)voicePath voiceDuration:(NSInteger)duration {
    NSLog(@"duration = %ld", duration);
    if (duration <= 1.0) {
        self.hudView.status = 2;
        [[NSFileManager defaultManager] removeItemAtPath:voicePath error:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.hudView hide];
        });
        return;
    } else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBox:sendVoiceMsg:voiceDuration:)]) {
            [self.delegate chatBox:self sendVoiceMsg:[voicePath componentsSeparatedByString:@"/"].lastObject voiceDuration:duration];
            [self.hudView hide];
        }
    }
}

#pragma mark - action
- (void)didClickVoiceBtnAction:(UIButton *)sender {
    if (sender == self.selectedBtn) {
        self.selectedBtn.selected = NO;
        self.selectedBtn = nil;
        self.talkBtn.hidden = YES;
        self.textView.superview.hidden = NO;
        [self.textView becomeFirstResponder];
        [self.textContentViewTopLayout activate];
        [self.talkBtnTopLayout deactivate];
        [self changeStatusTo:ChatBoxStatusKeyboard];
    } else {
        self.selectedBtn.selected = NO;
        self.selectedBtn = sender;
        self.selectedBtn.selected = YES;
        self.talkBtn.hidden = NO;
        self.textView.superview.hidden = YES;
        [self.textContentViewTopLayout deactivate];
        [self.talkBtnTopLayout activate];
        [self.textView resignFirstResponder];
        [self changeStatusTo:ChatBoxStatusVoice];
    }
}

- (void)didClickFaceBtnAction:(UIButton *)faceBtn {
    
    if (faceBtn == self.selectedBtn) {
        self.selectedBtn.selected = NO;
        self.selectedBtn = nil;
        [self.textContentViewTopLayout activate];
        [self.talkBtnTopLayout deactivate];
        [self changeStatusTo:ChatBoxStatusKeyboard];
        [self.textView becomeFirstResponder];
        
    } else {
        
        self.selectedBtn.selected = NO;
        self.selectedBtn = faceBtn;
        self.selectedBtn.selected = YES;
        self.talkBtn.hidden = YES;
        self.textView.superview.hidden = NO;
        [self.textView resignFirstResponder];
        [self changeStatusTo:ChatBoxStatusFace];
    }
}
- (void)didClickMoreBtnAction:(UIButton *)moreBtn {
    if (moreBtn == self.selectedBtn && self.status == ChatBoxStatusMore) {
        self.selectedBtn = nil;
        [self.textContentViewTopLayout activate];
        [self.talkBtnTopLayout deactivate];
        [self changeStatusTo:ChatBoxStatusKeyboard];
        [self.textView becomeFirstResponder];
    } else {
        self.selectedBtn.selected = NO;
        self.selectedBtn = moreBtn;
        self.talkBtn.hidden = YES;
        self.textView.superview.hidden = NO;
        [self.textView resignFirstResponder];
        [self changeStatusTo:ChatBoxStatusMore];
    }
}
- (void)didClickSendMsgBtnAction:(UIButton *)sendBtn {
    if (self.textView.attributedText.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBox:sendTextMsg:)] == YES) {
            [self.delegate chatBox:self sendTextMsg:[self plainText]];
             NSAttributedString *__xxxxStr = [[NSAttributedString alloc] initWithString:@" " attributes:@{NSForegroundColorAttributeName: UIColor.k_t2Color}];
            self.textView.attributedText = __xxxxStr;
            self.textView.attributedText = nil;
//            self.textView.typingAttributes = nil;

            self.textView.text = nil;
            
        }
    } else {
        self.textView.attributedText = nil;
        self.textView.text = nil;
//        [self textViewDidChange:self.textView];
    }
}


- (void)changeStatusTo:(ChatBoxStatus)newStatus {
    
    ChatBoxStatus lastStatus = self.status;
    self.status = newStatus;
    
    if ((newStatus == ChatBoxStatusKeyboard || newStatus == ChatBoxStatusFace || newStatus == ChatBoxStatusNothing) && [NSString isEmpty:self.textView.attributedText.string] == NO) {
        
        [self.faceRightLayoutWithMoreBtn deactivate];
        [self.faceRightLayoutWithSendBtn activate];
        self.sendBtnLayoutForWidth.offset(40);
        [UIView animateWithDuration:0.2 animations:^{
            self.moreBtn.alpha = 0;
        }];
        
    } else {
        [self.faceRightLayoutWithMoreBtn activate];
        [self.faceRightLayoutWithSendBtn deactivate];
        self.sendBtnLayoutForWidth.offset(0);
        [UIView animateWithDuration:0.4 animations:^{
            self.moreBtn.alpha = 1;
        }];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBox:changeFromStatus:toStatus:)] == YES) {
        [self.delegate chatBox:self changeFromStatus:lastStatus toStatus:newStatus];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBox:changeChatBoxViewHeight:)]) {
        [self.delegate chatBox:self changeChatBoxViewHeight:self.keyboardHeight];
    }
}

@end
